package com.smdk.dsminio.utils;
import cn.hutool.log.StaticLog;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {

    /**
     * 过期时间为15分钟
     */
    // private static final long EXPIRE_TIME = 1*60*1000;

    /**
     * token私钥
     */
    private static final String TOKEN_SECRET = "SMDKKAI";

    public static String encode(String info, String ip){
        //私钥及加密算法
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
        //设置头信息
        HashMap<String, Object> header = new HashMap<>(2);
        header.put("type", "JWT");
        header.put("alg", "HS256");
        //附带username和userID生成签名
        return JWT.create().withHeader(header).withClaim("ip", ip).withClaim("userInfo",info).sign(algorithm);
    }


    public static Map<String, String> decode(String token, String ip){
        DecodedJWT jwt;
        Map<String, Claim> map = null;
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).build();
            jwt = verifier.verify(token);
            map = jwt.getClaims();
        } catch (Exception e) {
            StaticLog.info("鉴权失败 token{} 鉴权ip",token,ip);
        }
        Map<String, String> resultMap = new HashMap<>();
        map.forEach((k, v) -> resultMap.put(k, v.asString()));
        return resultMap;
    }
}
